package manning.chapterTwo;
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UploadImage extends ActionSupport{
	public String execute(){
	System.out.println("###getpath: "+ getFileSystemPath());
	System.out.println("###getImageContentType: "+ getImageContentType());
	System.out.println("###getImageFileName: "+ getImageFileName());
	try{
			addImage(image, imageFileName, "C:\\");
	}catch(IOException ioex){
			ioex.printStackTrace();
	}
	
		return "SUCCESS";
	}
	
	public void addImage(File image, String imageFileName, String fileSystemPath) throws IOException{
		FileInputStream fin = null;
		FileOutputStream fout = null;
		
		File folder = new File(fileSystemPath);
		
		if(! folder.exists())
			folder.mkdir();
		
		String targetPath = folder.getPath() + folder.separator + imageFileName;
		System.out.println("Writing file to path: " + targetPath);
		try{
			fin = new FileInputStream(image);
			fout = new FileOutputStream(new File(targetPath));
			int c;
			while( (c = fin.read()) != -1 )
				fout.write(c);
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(fin!=null)
				fin.close();
			if(fout != null)
			fout.close();
				
		}
	}


//JavaBean code
private File image;
private String imageContentType;
private String imageFileName;
private String fileSystemPath;

			public File getImage(){
				return image;
			}
			public void setImage(File image){
				this.image = image;
			}
			public String getImageContentType(){
				return imageContentType;
			}
			public void setImageContentType(String imageContentType){
				this.imageContentType = imageContentType;
			}
			public String getImageFileName(){
				return imageFileName;
			}
			public void setImageFileName(String imageFileName){
				this.imageFileName = imageFileName;
			}
			public void setFileSystemPath(String fileSystemPath) {
					this.fileSystemPath = fileSystemPath;
			}
				
			public String getFileSystemPath() {
					return fileSystemPath;
			}

//Validation Code
public void validate(){
	if(getImage().length()==0){
		addFieldError("image", "Please select an image to upload.");
	}
}

}